<template>
  <div class="category-box-item">
    <div class="search">
      <n-input v-model:value="searchValue" clearable type="text" :placeholder="placeholder"></n-input>
    </div>
    <ul ref="ulRef">
      <n-spin v-if="loading" class="center" size="small" />
      <template v-else>
        <template v-if="categoryList[0]">
          <li
            v-for="item in categoryList"
            :key="item.id"
            :class="{ selected: item.id === value.categoryId }"
            @click="handleClickCategoryItem(item)"
          >
            {{ item.categoryName }}
          </li>
        </template>

        <n-empty v-else-if="!parentId" class="center" :show-icon="false" :description="emptyText" />
      </template>
    </ul>
  </div>
</template>

<script setup lang="ts">
  import { computed, nextTick, onMounted, ref, watch } from 'vue'
  import { NInput, NEmpty, NSpin } from 'naive-ui'
  import { useStore } from '@/store'

  const props = defineProps({
    value: {
      type: Object,
      default: () => ({
        categoryName: '',
        categoryId: null
      })
    },
    level: {
      type: Number,
      default: 1
    },

    parentId: {
      type: Number,
      default: null
    }
  })

  const emits = defineEmits(['update:value'])

  const store = useStore()
  const searchValue = ref('')
  const categoryListRow = ref<{ categoryName: string; id: number }[]>([])
  const loading = ref(false)
  const categoryList = computed(() => {
    const query = searchValue.value.trim()
    return query
      ? categoryListRow.value.filter((item) =>
          item.categoryName.toLocaleLowerCase().includes(query.toLocaleLowerCase())
        )
      : categoryListRow.value
  })
  const placeholder = computed(() => {
    if (props.level === 1) {
      return '搜索一级类目'
    } else if (props.level === 2) {
      return '搜索二级类目'
    } else if (props.level === 3) {
      return '搜索三级类目'
    }
    return '请输入'
  })
  const ulRef = ref(null)

  const emptyText = computed(() => {
    if (props.level === 1) {
      return '无数据'
    } else if (props.level === 2) {
      return '请先选择一级类目'
    } else if (props.level === 3) {
      return '请先选择二级类目'
    }
    return '无数据'
  })

  onMounted(() => {
    if (props.level === 1) {
      getCategoryList()
    }
  })

  watch(
    () => props.parentId,
    (value, oldValue) => {
      if (!value) {
        handleClearData()
      } else {
        getCategoryList()
      }
    }
  )

  watch(
    () => props.value,
    (value, oldValue) => {
      if (props.level === 1) {
        nextTick(() => {
          scrollIntoView()
        })
      }
    }
  )

  async function getCategoryList() {
    loading.value = true
    const { data } = await store
      .dispatch('product/getProductCategory', {
        parentId: props.parentId
      })
      .finally(() => {
        loading.value = false
      })

    categoryListRow.value = data || []
    if (props.value.categoryId) {
      const selected = categoryListRow.value.find((item) => item.id === props.value.categoryId)
      if (selected) {
        handleClickCategoryItem(selected, 'backfill')
      }
    }
  }

  function handleClickCategoryItem(item, type?: string) {
    emits(
      'update:value',
      {
        ...item,
        categoryId: item.id
      },
      type
    )

    nextTick(() => {
      scrollIntoView()
    })
  }

  function scrollIntoView() {
    const dom = ulRef.value?.querySelector('li.selected')
    if (dom) {
      dom.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }

  function handleClearData() {
    categoryListRow.value = []
  }
</script>

<style scoped lang="scss">
  @import '@/assets/styles/var.scss';
  .category-box-item {
    height: 100%;
    overflow: hidden;
    ul {
      position: relative;
      height: calc(100% - 34px);
      background: #ffffff;
      border: 1px solid rgb(224, 224, 230);
      border-top: none;
      border-radius: 0 0 3px 3px;
      overflow-y: auto;
      scrollbar-width: none; /* firefox */
      &::-webkit-scrollbar {
        display: none; /* Chrome Safari */
      }
      li {
        line-height: 32px;
        padding-left: 12px;
        background-color: #fff;
        cursor: pointer;

        &:hover {
          background-color: #fafafa;
        }

        &.selected {
          background-color: #eeefff;
          color: $primaryColor;
        }
      }

      .center {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate3d(-50%, -50%, 0);
      }
    }
  }
</style>
